import { AmcaxForm, CommandDialog, pickedLineData } from '@amcax/base';
import i18n from '@app-cad/common/utils/i18next';
import { NMTopoBaseCommand } from '@app-cad/environments/nextmesh/types/command';
import { PickInputForFocus } from '@app-cad/common/components/command-form/auto-focus/pick-input';
import { CommandFormWrapper } from '@app-cad/common/components/command-form';
import { GenerateMode, TopoDialogProps } from '../type';
import { useState } from 'react';
import { CommandFormFooter } from '@app-cad/common/components/command-form/footer';
import { documentV2 } from '@app-nextmesh/domain';
import validator from '@rjsf/validator-ajv8';
import { useCommand } from '@app-base/common/hooks/useCommand';
import { Button, Popover } from 'antd';
import { DirectionGroup } from '../cmd-direction';
import { RJSFSchema } from '@rjsf/utils';
import { PickInputValueType } from '@app-base/common/components/pick-input/types';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
function TopoRotateDialog({ title, onClose }: TopoDialogProps) {
  const [rotateEdgeData, setRotateEdgeData] = useState<pickedLineData[]>([]);
  const [rotateAxisData, setRotateAxisPathData] = useState<pickedLineData[]>(
    [],
  );
  const [directionBtnVisible, setDirectionBtnVisible] = useState(false);
  const [buttonText, setButtonText] = useState('请选择旋转方向');
  const [directionVisible, setDirectionVisible] = useState(false);
  const [directionData, setDirectionData] = useState([]);
  const [length, setLength] = useState(0);
  // 旋转角度
  const [rotateAngle, setRotateAngle] = useState(0);
  useCommand('cmdTopoRotate', {
    onClose,
  });
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      angle: {
        type: 'number',
        title: '角度',
        default: 0,
        minimum: 0,
        maximum: 360,
      },
    },
  };
  const uiSchema: RJSFSchema = {
    'ui:submitButtonOptions': {
      norender: true,
    },
  };
  const onRotateEdgeData = (data) => {
    setRotateEdgeData(data);
  };
  const onRotateAxisData = (data) => {
    if (data?.length > 0) {
      for (const item of data) {
        if ('vertexId' in item) {
          setDirectionBtnVisible(true);
        }
      }
      setRotateAxisPathData(data);
    }
  };
  const handleSubmit = async () => {
    const relyOn = directionBtnVisible
      ? directionData.map((item) => {
          return item * length;
        })
      : [rotateAxisData[0].edgeId];
    const params = {
      source: [rotateEdgeData[0].edgeId],
      relyOn,
      mode: GenerateMode.Rotate,
      param: [rotateAngle],
    };
    await documentV2.generateEntity(params);
    onClose();
  };
  const isValid = () => {
    if (directionBtnVisible) {
      return rotateEdgeData.length > 0 && directionData.length > 0;
    } else {
      return rotateEdgeData.length > 0 && rotateAxisData.length > 0;
    }
  };
  const onDirectionData = (data) => {
    setDirectionVisible(data.directionVisible);
    setButtonText(data.buttonText);
    setDirectionData(data.directionVec);
    setLength(data.length);
  };
  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      onClose={onClose}>
      <CommandFormWrapper>
        <PickInputForFocus
          autoFocus
          controlled
          allowPickType={[PickInputValueType.Line, PickInputValueType.Curve]}
          onPick={onRotateEdgeData}
          value={rotateEdgeData}
          placeholder='请选择旋转的边'
        />
        <PickInputForFocus
          allowPickType={[PickInputValueType.Line, PickInputValueType.Vertex]}
          controlled
          onPick={onRotateAxisData}
          value={rotateAxisData}
          placeholder='请选择旋转轴'
        />
        <Popover
          getPopupContainer={() => document.querySelector('#app-cad_root')}
          trigger='click'
          title='拉伸方向'
          open={directionVisible}
          content={<DirectionGroup onDirectionSubmit={onDirectionData} />}>
          {directionBtnVisible && (
            <Button onClick={() => setDirectionVisible(true)}>
              {buttonText}
            </Button>
          )}
        </Popover>
        <AmcaxForm
          className='topo-rotate'
          schema={schema}
          uiSchema={uiSchema}
          validator={validator}
          formContext={formItemLayout}
          onChange={(data) => {
            setRotateAngle(data.formData.angle);
          }}
        />
        <CommandFormFooter
          onClose={onClose}
          onSubmit={handleSubmit}
          submitText='确定'
          isSubmitDisabled={!isValid()}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}
export const cmdTopoRotate: NMTopoBaseCommand = {
  id: 'TopoRotateDialog',
  icon: 'commands/curved/point',
  label: 'command.topo.rotate',
  create: (label: string, onClose: () => void, props) => (
    <TopoRotateDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
